<template>
  <div style="height: 100%; padding: 10px;" class="DimensionOrg-page">
    <!-- <FormBlock title="组织树" direction="column" style="width:100%; overflow-x: hidden;" height="500px"> -->
    <AutoComplete
      v-model="nameOrCode"
      @input="onSearch"
      @on-change="onChange"
      @on-select="onSelectSearch"
      @on-clear="onClear"
      :placeholder="$t('common.warning.searchOrg')"
      style="padding: 0px 0 5px 0; margin: auto; display: block;"
      icon="md-search"
      clearable
    >
      <Option v-for="(option, index) in searchResult" :value="option" :key="index">{{option}}</Option>
      <p
        class="complete-more get-complete-more"
        v-if="searchResult.length >= 10 && isShowMore"
        @click="showMore"
      >{{ $t('common.showMore') }}</p>
    </AutoComplete>
    <!-- <Spin v-if="isShowSpin">{{ searchHint }}</Spin> -->
    <el-tree
      ref="tree"
      lazy
      :data="treeData"
      :props="treeProps"
      node-key="orgId"
      @node-click="onNodeClick"
      :expand-on-click-node="false"
      class="tree-box"
      icon-class="ivu-icon-ios-arrow-forward"
      highlight-current
      :load="loadData"
      :default-expanded-keys="expandedKeys"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <Tooltip :content="$t('common.frozen')" :disabled="data.enabled != 0" placement="top">
          <embed
            src="static\images\enterprise.svg"
            width="10"
            height="10"
            type="image/svg+xml"
            v-if="data.orgType == 1"
            class="node-svg"
          />
          <embed
            src="static\images\company.svg"
            width="10"
            height="10"
            type="image/svg+xml"
            v-if="data.orgType == 2"
          />
          <embed
            src="static\images\department.svg"
            width="10"
            height="10"
            type="image/svg+xml"
            v-if="data.orgType == 10"
          />
          <span
            :class="data.enabled == 0 ? 'invalidStyle' : ''"
            class="node-label"
            :title="node.label"
          >{{ node.label }}</span>
        </Tooltip>
      </span>
    </el-tree>
    <!-- </FormBlock> -->
  </div>
</template>
<script>
import orgAssignRoleAPI from "@/api/orgAssignRoleAPI.js";
import { searchDelayTime } from "@/const.js";
import locales from "./locales.js";

export default {
  mixins: [locales],
  components: {},
  props: {
    dimensionId: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    return {
      pageNum: 1,
      isShowMore: true,
      orgList: [],
      expandedKeys: [],
      fun: null,
      treeData: [],
      treeProps: {
        label: "orgName",
        children: "childrenDept",
        isLeaf: "isLeaf"
      },
      nameOrCode: "",
      searchResult: [],
      searchResultNode: [],
      pressCount: 0,
      isShowSpin: false
    };
  },
  computed: {},
  created: function() {
    this.initTree();
  },
  methods: {
    showMore() {
      this.getSelectNode(this.nameOrCode);
    },
    getSelectNode(value) {
      // 点击查看更多，pageNum改为2，从第二页开始查询
      this.pageNum++;
      if (value && value.indexOf("/") == -1) {
        let param = {
          condition: {
            enabled: 1,
            nameOrCode: value,
            orgTypeFilter: 3,
            dimensionRelId: this.dimensionId
          },
          pageNum: this.pageNum,
          pageSize: 10
        };
        orgAssignRoleAPI.queryOrgRootNode(param).then(data => {
          if (data.records != null && data.records.length > 0) {
            this.loading = false;
            let pathArr = [];
            let orgArr = [];
            const list = data.records.map(item => {
              pathArr.push(item.orgNameFullPath);
            });

            orgArr = data.records;

            this.$nextTick(() => {
              this.searchResult = this.searchResult.concat(pathArr);
              this.orgList = this.orgList.concat(orgArr);
            });
          } else {
            // 查询结果，data.records为空数组时，隐藏查看更多按钮
            this.isShowMore = false;
          }
        });
      }
    },
    loadData(node, resolve) {
      if (node.level == 0) {
        // 隐藏根节点
        return;
      }
      // 是叶子节点不进行查询
      if (node.isLeaf) {
        resolve([]);
      }
      let param = {
        condition: {
          enabled: 1,
          orgPath: node.data.orgPath,
          nameOrCode: this.nameOrCode,
          orgTypeFilter: 3,
          dimensionRelId: this.dimensionId
        },
        pageNum: 1,
        pageSize: 10
      };
      orgAssignRoleAPI.queryOrgRootNode(param).then(children => {
        resolve(children.records);
      });
    },
    initTree() {
      // 查询树节点
      let param = {
        condition: {
          enabled: 1,
          nameOrCode: "",
          orgTypeFilter: 3,
          dimensionRelId: this.dimensionId
        },
        pageNum: 1,
        pageSize: 10
      };
      orgAssignRoleAPI.queryOrgRootNode(param).then(data => {
        // 选中根节点
        if (data.records && data.records.length > 0) {
          this.treeData = data.records;
          this.$nextTick(function() {
            this.selectFirstNode(data.records[0]);
            this.onNodeClick(data.records[0]);
          });
        }
      });
    },
    selectFirstNode(node) {
      this.$refs["tree"].setCurrentKey(node.orgId);
    },
    onNodeClick(data) {
      this.$emit("change", data.assignmentId);
    },
    //   防抖函数
    debounce(fn, wait = 1000) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    setTimeSearch(value) {
      this.pageNum = 1; // 当重新搜索时，默认从第一页开始查询
      this.isShowMore = true; // 当重新搜索时，默认显示查看更多
      this.searchResult = []; //数组中只包含orgNameFullPath
      this.orgList = []; // 数组中包含orgId orgNameFullPath orgName orgPath
      let param = {
        condition: {
          enabled: 1,
          nameOrCode: this.nameOrCode,
          orgTypeFilter: 3,
          dimensionRelId: this.dimensionId
        },
        pageNum: 1,
        pageSize: 10
      };
      orgAssignRoleAPI.queryOrgRootNode(param).then(data => {
        if (data.records != null) {
          this.orgList = data.records;
          const list = data.records.map(item => {
            this.searchResult.push(item.orgNameFullPath);
          });
        }
      });
    },
    onSearch(value) {
      this.debounce(() => {
        this.setTimeSearch(value);
      }, 300);
    },
    onChange(value) {},
    onSelectSearch(value) {
      this.expandedKeys = [];
      this.$refs.tree.store.lazy = false;
      let data = this.orgList.filter(item => {
        if (item.orgNameFullPath == value) {
          this.expandedKeys.push(item.orgId);
          return item.orgId;
        }
      });
      let selectOrg = data[0];
      orgAssignRoleAPI
        .getTreeBySelectOrg({ orgId: selectOrg.orgId, dimensionRelId: this.dimensionId })
        .then(data => {
          this.treeData = data;
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.expandedKeys[0]);
            this.$emit("change", selectOrg.assignmentId);
          });
        })
        .catch(err => {});
    },
    onClear() {
      this.searchResult = [];
      this.nameOrCode = "";
      this.expandedKeys = [];
      this.$refs.tree.store.lazy = true;
      this.initTree();
    }
  },
  watch: {
    nameOrCode: {
      handler(value) {
        if (!value) {
          this.onClear();
        }
      },
      deep: true
    }
  },
  directives: {}
};
</script>
<style lang="less">
.DimensionOrg-page {
  .ivu-select-dropdown {
    max-height: 330px !important;
    .ivu-select-dropdown-list {
      width: fit-content;
      .ivu-select-item:hover {
        background: #fff !important;
      }
    }
  }
  overflow-x: auto;
  .el-tree-node > .el-tree-node__children {
    overflow: inherit;
  }
  .node-svg {
    position: relative;
    top: 2px;
  }
  .node-label {
    margin-left: 3px;
  }
}
</style>
